package zdream.pmfield.stage.buff.ability;

import zdream.pmfield.data.foe.MoveAdditionalEffects;
import zdream.pmfield.data.foe.Type;
import zdream.pmfield.stage.buff.foe.TypeBuff;
import zdream.pmfield.stage.director.AttackContext;
import zdream.pmfield.stage.director.FixPair;
import zdream.pmfield.stage.director.Hooks;
import zdream.pmfield.stage.director.Roll;
import zdream.pmfield.stage.object.StageMove;

import static zdream.pmfield.stage.director.HookType.ON_CHECK_TYPE_FIXED;

/**
 * 龙族效果:
 * <li>对水、火、电增加 0.5 级的抗性
 * ({@link zdream.pmfield.data.foe.Type.TypeWithWeight#weight} 为 0.5)
 * <li>对冰减少 1 级的抗性
 * <li>所有本系加成失效
 * </li>
 *
 * @author Zdream
 * @date 2023-12-18
 * @since 0.0.1
 */
public class DragonGroupBuff extends AbilityBuff {
	public static final String CATEGORY = MoveAdditionalEffects.A_DRAGON_GROUP;

	public DragonGroupBuff(BuffDescription description) {
		super(description);
	}

	@Override
	public void init() {
		onHook(ON_CHECK_TYPE_FIXED)
				.handle(this::checkTypeFixedWhenIAmDefender)
				.buildAndSave();
		onHook(ON_CHECK_TYPE_FIXED)
				.handle(this::checkTypeFixedWhenIAmAttacker)
				.buildAndSave();
	}

	public void checkTypeFixedWhenIAmDefender(Hooks.HookContext rawContext) {
		Hooks.AttackHookContext context = rawContext.as();
		final AttackContext attackContext = context.attackContext;
		final AttackContext.AttackContextItem item = attackContext.findAttackItemForDefender(target);

		if (item == null) {
			return;
		}

		final StageMove move = attackContext.currentMove;
		if (move.hasType(Type.WATER)) {
			item.typeFixPairs.add(FixPair.ofDefender(0.5f * move.weightOfType(Type.WATER), (byte)-1, CATEGORY));
		}
		if (move.hasType(Type.FIRE)) {
			item.typeFixPairs.add(FixPair.ofDefender(0.5f * move.weightOfType(Type.FIRE), (byte)-1, CATEGORY));
		}
		if (move.hasType(Type.ELECTRIC)) {
			item.typeFixPairs.add(FixPair.ofDefender(0.5f * move.weightOfType(Type.ELECTRIC), (byte)-1, CATEGORY));
		}
		if (move.hasType(Type.ICE)) {
			item.typeFixPairs.add(FixPair.ofDefender(move.weightOfType(Type.ICE), (byte)1, CATEGORY));
		}
	}

	public void checkTypeFixedWhenIAmAttacker(Hooks.HookContext rawContext) {
		Hooks.AttackHookContext context = rawContext.as();
		final AttackContext attackContext = context.attackContext;
		if (!attackContext.hasAttacker(target)) {
			return;
		}

		final Roll[] moreRolls = attackContext.moreRolls;
		if (moreRolls != null) {
			for (Roll moreRoll : moreRolls) {
				if (moreRoll.createdBy.is(TypeBuff.CATEGORY)) {
					moreRoll.affectedBy = this;
					moreRoll.affectResult = false;
					moreRoll.refresh();
				}
			}
		}
	}

	@Override
	public String getCategory() {
		return CATEGORY;
	}

	@Override
	public String toString() {
		return "龙族";
	}
}
